﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace DLLWrapper
{
    public class HGDLLWrapper
    {

        /// load libary
        ///  
        [DllImport("Kernel32.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr LoadLibrary(string lpFileName);

        [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
        public static extern int GetProcAddress(
            IntPtr hModule, string lpProcName);

        [DllImport("kernel32.dll", EntryPoint = "FreeLibrary", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
        public static extern bool FreeLibrary(IntPtr hModule);


        public static Delegate GetFunctionAddress(IntPtr dllModule, string functionName, Type t)
        {

            int address = GetProcAddress(dllModule, functionName);

            if (address == 0)

                return null;

            else

                return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);

        }
        public static Delegate GetDelegateFromIntPtr(IntPtr address, Type t)
        {

            if (address == IntPtr.Zero)

                return null;

            else

                return Marshal.GetDelegateForFunctionPointer(address, t);

        }



        ///<summary>

        ///将表示函数地址的int转换成对应的委托，by jingzhongrong

        ///</summary>

        public static Delegate GetDelegateFromIntPtr(int address, Type t)
        {

            if (address == 0)

                return null;

            else

                return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);

        }
        /// </summary>
        /// <returns></returns>
        //[DllImport("BrightnessControl.dll", EntryPoint = "GetDllVersion", CharSet = CharSet.Auto)]
        //public static extern int GetDllVersion();
        //[DllImport("BrightnessControl.dll", EntryPoint = "GetFirmwareInfo", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
        //public static extern bool GetFirmwareInfo(ref FirmwareInfo Info);




        [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)]
        public struct FirmwareInfo
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public byte[] version;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
            public byte[] vendor_name;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
            public byte[] product_name;

            public void Init()
            {
                version = new byte[16];
                vendor_name = new byte[256];
                product_name = new byte[256];

                //pitchData = null;
            }


        }
    }
}
